package com.cobra.controller;

import com.cobra.util.FileUtil;
import com.cobra.util.ZipUtil;
import net.lingala.zip4j.core.ZipFile;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;

@RestController
public class ZipController {

    String path = "src/main/resources/zipFile/test.txt";
    String zipPath = "src/main/resources/zipFile/zip/test-zip.zip";
    String unzipPath = "src/main/resources/zipFile/zip/";

    String password = "123456";
    @RequestMapping("/zip")
    public ResponseEntity zip(boolean isDelete) throws Exception {
        ZipFile zipFile = ZipUtil.zipFile(path, zipPath, true, password);
        String absolutePath = zipFile.getFile().getAbsolutePath();
        InputStreamResource resource = new InputStreamResource(new FileInputStream(absolutePath));
        String name = zipFile.getFile().getName();
        HttpHeaders headers = new HttpHeaders();
        //指定文件名
        headers.setContentDispositionFormData("attachment", new String(name.getBytes("UTF-8"),"ISO-8859-1"));
        ResponseEntity<InputStreamResource> body = ResponseEntity.ok()
                .headers(headers)
                .contentLength(zipFile.getFile().length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
        if(isDelete){
            FileUtil.deleteFile(zipPath);
        }
        return body;
    }

    @RequestMapping("/unzip")
    public String unzip() throws Exception{
        ZipUtil.unzip(zipPath,unzipPath,true,password);
        return "success";
    }
}
